import React, { useEffect, useState, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { Spin } from 'antd';
import { usePagePreloader } from '../hooks/usePagePreloader';

interface SmartRouteProps {
  path: string;
  component: React.ComponentType<any>;
  preloadDelay?: number;
  backgroundKeepAlive?: boolean;
  children?: React.ReactNode;
}

const SmartRoute: React.FC<SmartRouteProps> = ({
  path,
  component: Component,
  preloadDelay = 1000,
  backgroundKeepAlive = true,
  children
}) => {
  const location = useLocation();
  const isCurrentPath = location.pathname === path;
  const [isPreloaded, setIsPreloaded] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const componentRef = useRef<HTMLDivElement>(null);
  
  const {
    preloadPage,
    activateCurrentPage,
    moveToBackground,
    isPreloaded: checkIsPreloaded,
    getPreloadedComponent
  } = usePagePreloader({
    preloadDelay,
    backgroundKeepAlive
  });

  // 预加载页面
  useEffect(() => {
    if (!checkIsPreloaded(path)) {
      preloadPage(path, Component).then(() => {
        setIsPreloaded(true);
      });
    } else {
      setIsPreloaded(true);
    }
  }, [path, Component, preloadPage, checkIsPreloaded]);

  // 处理页面激活和后台切换
  useEffect(() => {
    if (isCurrentPath && isPreloaded) {
      activateCurrentPage(path);
      setIsLoading(false);
    } else if (!isCurrentPath && backgroundKeepAlive && isPreloaded) {
      moveToBackground(path);
    }
  }, [isCurrentPath, isPreloaded, activateCurrentPage, moveToBackground, path, backgroundKeepAlive]);

  // 如果当前路径不匹配，不渲染
  if (!isCurrentPath) {
    return null;
  }

  // 如果正在加载，显示loading
  if (isLoading || !isPreloaded) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        color: 'white'
      }}>
        <div style={{ textAlign: 'center' }}>
          <Spin size="large" style={{ color: 'white' }} />
          <div style={{ marginTop: '20px', fontSize: '16px' }}>
            正在加载页面...
          </div>
        </div>
      </div>
    );
  }

  // 渲染页面组件
  return (
    <div ref={componentRef} style={{ height: '100%' }}>
      <Component />
      {children}
    </div>
  );
};

export default SmartRoute;
